﻿
using TrainGame.Model;
namespace TrainGame.AI
{
	/// <summary>
	/// AI utility functions
	/// </summary>
	static internal class AiUtils
	{
		/// <summary>
		/// Get the maximum value for a city, based on the game phase and available upgrade tiles
		/// </summary>
		/// <param name="city"></param>
		/// <param name="tiles"></param>
		/// <param name="config"></param>
		/// <returns></returns>
		static public int GetMaxCityValue(City city, Tiles tiles, AiMoveConfig config)
		{
			// offboard increase only as phases advance
			if (city.Offboard)
				return city.Value;

			// towns are $10 unless in gray phase, where they can upgrade to brown $40's
			if ((city.CityType == GameboardHex.eTownType.Town) || (city.CityType == GameboardHex.eTownType.DblTown))
			{
				if (config.AllowGrayTile)
					return 40;	// towns can upgrade to browns
				return 10;	// yellow or green town
			}

			// more general solution for all other tiles
			Tile.eTileColor lastColor;
			if (config.AllowGrayTile)
				lastColor = Tile.eTileColor.Gray;
			else if (config.AllowBrownTile)
				lastColor = Tile.eTileColor.Brown;
			else if (config.AllowGreenTile)
				lastColor = Tile.eTileColor.Green;
			else
				lastColor = Tile.eTileColor.Yellow;

			int value = city.Value;
			Tile tile = city.Hex.Tile;
			if (tile != null)	// otherwise we got here by initial track in the hex
			{
				while (tile.Color != lastColor)
				{
					// if no upgrades, we're done
					if ((tile.ValidUpgrades == null) || (tile.ValidUpgrades.Count == 0))
					{
						// EXCEPT for wierd tiles like green Barrie-London, which has two different upgrade paths for the
						// two different cities, and ValidUpgrades is empty.  For those cases we'll also check hex.FinalTile
						if (string.IsNullOrEmpty(city.Hex.FinalTile) || (tile.Name == city.Hex.FinalTile))	// or already at that tile
							return value;
						tile = tiles[city.Hex.FinalTile];
						if (tile.QuantityLeft == 0)
							return value;
					}
					else
					{
						bool found = false;
						foreach (string testTile in tile.ValidUpgrades)
						{
							if (tiles[testTile].QuantityLeft > 0)
							{
								tile = tiles[testTile];
								found = true;
								break;
							}
						}
						if (!found)
							return value;
					}

					value = tile.Worth;
				}
			}
			return value;
		}
	}
}
